define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'layui', 'template'], function ($, undefined, Backend, Table, Form, Layui, Template) {

    var Controller = {
        index: function () {
            layui.use(['tree', 'util'], function () {
                var tree = layui.tree;
                tree.render({
                    elem: '#test4',
                    data: Config.admin.school,
                    accordion: true,
                    click: function (obj) {
                        var data = obj.data;
                        if (data.type == 'classes') {
                            $('.selected').removeClass('selected');
                            $(obj.elem).find('.layui-tree-main').addClass('selected');
                            $('input[name=school_id]').val(data.school_id)
                            $('input[name=class_id]').val(data.id)
                            Controller.api.semesterList();
                        }
                    }
                });
            });

            var container = document.getElementById("divcontainer");
            //得到允许拖拽的dom元素，如果没有，返回undefined
            function getAllowedDom(target) {
                if (target.dataset.allowed === "true") {
                    return target;
                }
                if (target.parentNode.dataset.allowed === "true") {
                    return target.parentNode;
                }
            }
            var curDiv; //拖放源
            container.ondragstart = function (e) {
                curDiv = e.target;
            };
            container.ondragover = function (e) {
                e.preventDefault(); //阻止默认拖拽行为
                var dom = getAllowedDom(e.target);
                if (dom) {
                    e.dataTransfer.dropEffect = dom.tagName === "DIV" ? "move" : "copy";
                } else {
                    e.dataTransfer.dropEffect = "none";
                }
            };
            //拖放进入的时候
            var beforeEnter;//记录的是之前背景改变的td
            container.ondragenter = function (e) {
                var dom = getAllowedDom(e.target);
                if (beforeEnter) {
                    beforeEnter.style.background = "";
                }
                if (dom && dom.tagName === "SPAN") {
                    dom.style.background = "#666";
                    beforeEnter = dom;
                }
            };
            //拖放出去的时候
            // container.ondragleave = function (e) {
            //     var dom = getAllowedDom(e.target);
            //
            //     if (dom && dom.tagName === "TD" && e.target.tagName === "TD") {
            //         dom.style.background = "";
            //     }
            // };
            container.ondrop = function (e) {
                var dom = getAllowedDom(e.target);
                if (!dom) {
                    return;
                }
                beforeEnter = null;
                dom.style.background = "";

                var dom_index, dom_day, parent_index, parent_day;
                if (curDiv.parentNode.tagName === "DIV" && dom.tagName === "SPAN") {
                    //复制
                    //console.log('复制')
                    var newDiv = curDiv.cloneNode(true);

                    dom_index = dom.dataset.index;
                    dom_day = dom.dataset.day;
                    var input = newDiv.lastElementChild;
                    input.name = 'course[' + dom_index + '][' + dom_day + ']';

                    dom.innerHTML = "";
                    dom.appendChild(newDiv);

                } else if (dom.tagName === "SPAN") {
                    //移动
                    //console.log('移动')
                    var before = dom.innerHTML;
                    var parent = curDiv.parentNode;

                    dom_index = dom.dataset.index;
                    dom_day = dom.dataset.day;
                    parent_index = parent.dataset.index;
                    parent_day = parent.dataset.day;

                    if (dom.lastElementChild && dom.lastElementChild.lastElementChild) {
                        var dom_input = dom.lastElementChild.lastElementChild;
                        dom_input.name = 'course[' + parent_index + '][' + parent_day + ']';
                        before = dom.innerHTML;
                    }
                    var parent_input = parent.lastElementChild.lastElementChild;
                    parent_input.name = 'course[' + dom_index + '][' + dom_day + ']';

                    dom.innerHTML = "";
                    dom.appendChild(curDiv);
                    parent.innerHTML = before;
                } else if (curDiv.parentNode.className !== 'left'){
                    //移除
                    console.log('移除');

                    console.log(curDiv);
                    console.log(dom);

                    curDiv.remove();
                }
            };

            $('#course-form').submit(function (event) {
                event.preventDefault();
                
                if ($('.btn-success').hasClass('disabled')) {
                    return false;
                }

                if (!$('input[name=school_id]').val() || !$('input[name=class_id]').val()) {
                    Backend.api.toastr.error('请选择班级！');
                    return false;
                }

                var targetUrl = $(this).attr("action");
                var data = $(this).serialize();
                $.ajax({
                    type: 'post',
                    url: targetUrl,
                    cache: false,
                    data: data,
                    dataType: 'json',
                    success: function (data) {
                        if (data.code) {
                            Backend.api.toastr.success('保存成功');
                        } else {
                            Backend.api.toastr.error(data.msg);
                        }
                    },
                    error: function () {
                        Backend.api.toastr.error('保存失败');
                    }
                });
            });

            $(document).on('change', '.semester', function () {
                Controller.api.semesterNumList();
            });

            $(document).on('change', '.semester_num', function () {
                Controller.api.schedule();
            });

        },
        api: {
            semesterList: function () {
                console.log($('.semester').val())
                if ($('.semester').val()) {
                    if ($('.semester_num').val()) {
                        Controller.api.schedule();
                    } else {
                        Controller.api.semesterNumList();
                    }
                } else {
                    $('.semester').html('');
                    $('.semester_num').html('');
                    $.ajax({
                        type: 'post',
                        url: 'semester/select',
                        cache: false,
                        data: {school_id: $('input[name=school_id]').val()},
                        dataType: 'json',
                        success: function (ret) {
                            $(".semester").html(Template("semesterTpl", ret));
                        },
                        error: function () {
                        }
                    });
                }
            },
            semesterNumList:function () {
                $('.semester_num').html('');
                $("#divcontainer .left").html('');
                $("#divcontainer .right").html('');
                $.ajax({
                    type: 'post',
                    url: 'semester/selectWeekList',
                    cache: false,
                    data: {id: $('.semester').val()},
                    dataType: 'json',
                    success: function (ret) {
                        $(".semester_num").html(Template("semesterTpl", ret));
                    },
                    error: function () {
                    }
                });
            },
            schedule:function () {
                $("#divcontainer .left").html('');
                $("#divcontainer .right").html('');
                $.ajax({
                    type: 'post',
                    url: '/admin/course/classroom/index',
                    cache: false,
                    data: {school_id: $('input[name=school_id]').val(), class_id: $('input[name=class_id]').val(), semester_id: $('.semester').val(), semester_num: $('.semester_num').val()},
                    dataType: 'json',
                    success: function (ret) {
                        $("#divcontainer .left").html(Template("teachersTpl", ret.data));
                        $("#divcontainer .right").html(Template("coursesTpl", ret.data));

                        $('.btn-success').removeClass('disabled');
                    },
                    error: function () {
                    }
                });
            }
        }
    };
    return Controller;
});